//定制请求实例
import axios from "axios";
import { ElMessage } from "element-plus";
//导入token
import { useTokenStore } from "@/store/token";
import router from "@/router";
import { useCustomerInfoStore } from "@/store/customerInfo";
import { useBusinessInfoStore } from "@/store/businessInfo";
import { useLoginStore } from "@/store/login";

//定义URL公共前缀
const baseURL = 'http://8.138.173.30:8080';
const instance = axios.create({baseURL});

//请求拦截器,在发送请求前在头部加上token
instance.interceptors.request.use(
    (config) => {
        const tokenStore = useTokenStore()
        config.headers.Customer = tokenStore.token
        return config
    },
    (err) => {
        Promise.reject(err)
    }
)

//响应拦截器
instance.interceptors.response.use(
    result => {
        //判断业务状态码
        if(result.data.code === 0) {
            return result.data
        }

        //操作失败
        ElMessage.error(result.data.message? result.data.message:'服务异常')
        //异步操作的状态转换为失败
        return Promise.reject(result.data)
    },
    err => {
        const currentPath = window.location.pathname;
        if(err.response.status === 401) {
            if(currentPath === '/') {
                const customerInfoStore = useCustomerInfoStore();
                const businessInfoStore = useBusinessInfoStore();
                const loginStore = useLoginStore();
                customerInfoStore.removeCustomerInfo();
                businessInfoStore.removeBusinessInfo();
                loginStore.removeLoginInfo();
                ElMessage.error('登录已过期，请重新登录');
                return Promise.reject("登录已过期，请重新登录");
            }
            ElMessage.error('请先登录！')
            router.push('/Login')
        }else {
            ElMessage.error('服务异常')
        }
        return Promise.reject(err);
    }
)

export default instance;